﻿using System;
using System.Net;
using System.Net.Sockets;
using Tools.Debugging;
using System.Text;

namespace repliback4.Net.ClientSide {
    public class Client {
        public delegate void OnConnectedHandler ( );
        public event OnConnectedHandler OnConnected;
        public Server server;
        public Client ( ) {

        }
        public void Connect ( String address, int port ) {
            IPAddress addr;
            if ( IPAddress.TryParse( address, out addr ) ) {
                this.Connect( addr, port );
            } else {
                try {
                    IPHostEntry hostEntry = Dns.GetHostEntry( address );
                    this.Connect( hostEntry.AddressList, port );
                } catch ( Exception e ) {
                    Logger.Debug(typeof(Client), String.Format("Host name resolving exception: {0}", e.Message));
                    throw e;
                }
            }
        }

        public void Connect ( IPEndPoint endpoint ) {
            this.Connect( endpoint.Address, endpoint.Port );
        }
        protected void Connect ( IPAddress address, int port ) {
            this.Connect( new IPAddress[] { address }, port );
        }
        protected void Connect ( IPAddress[] addresses, int port ) {
            TcpClient client = new TcpClient( );
            client.BeginConnect( addresses, port, new AsyncCallback( this.OnConnect ), client );
        }
        private void OnConnect ( IAsyncResult result ) {
            try {
                TcpClient client = ( TcpClient ) result.AsyncState;
                client.EndConnect( result );

                if ( client.Connected ) {
                    this.server = new Server( client );
                    if ( this.OnConnected != null ) this.OnConnected( );
                } else {
                    throw new Exception( "Client not conneted" );
                }
            } catch ( SocketException e ) {
                Logger.Debug( typeof( Client ), String.Format( "Socket Exception: {0}", e.Message ) );
            } catch ( Exception e ) {
                Logger.Debug( typeof( Client ), String.Format( "Exception: {0}", e.Message ) );
            }
        }
        public void HttpRequestForContent ( ) {
            Console.WriteLine( "requesting..." );

            StringBuilder sb = new StringBuilder( );
            //http://test.thesebas.net/info.php?SERVER
            sb.AppendLine( "GET /info.php?SERVER HTTP/1.1" );
            sb.AppendLine( "Host: test.thesebas.net" );
            sb.AppendLine( "Keep-Alive: 10" );
            sb.AppendLine( "Connection: keep-alive" );
            sb.AppendLine( );
            this.server.Send( sb.ToString( ) );

        }
    }
}
